<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="formRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="频道ID" prop="channelId">
        <el-input
          v-model.trim="queryParams.channelId"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="enable">
        <el-radio-group v-model="queryParams.enable">
          <el-radio label="" value="">全部</el-radio>
          <el-radio :label="true" :value="true">启用</el-radio>
          <el-radio :label="false" :value="false">未启用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model.trim="queryParams.remark"
          placeholder="请输入"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">
          搜索
        </el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="batchAddAll">批量新增</el-button>
      </el-col>
    </el-row>
    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="poolList" :row-style="rowStyle">
      <el-table-column type="selection" width="55" :align="`center`" />

      <!-- <el-table-column label="id" prop="id" width="200"> </el-table-column> -->
      <el-table-column label="频道ID" prop="channelId" width="200">
      </el-table-column>
      <el-table-column label="token" prop="userToken" width="260">
      </el-table-column>
      <el-table-column label="状态" prop="enable" width="150">
        <template #default="{ row }">
          <el-tag :type="row.enable ? 'success' : 'danger'" effect="light">
            {{ row.enable ? '启用' : '未启用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="快速时间剩余"
        prop="fastTimeRemaining"
        width="200"
      >
      </el-table-column>
      <el-table-column label="备注" prop="remark" width="100">
      </el-table-column>
      <el-table-column label="订阅计划" prop="subscribePlan" width="150">
      </el-table-column>
      <el-table-column label="续订时间" width="150">
        <template #default="{ row }">
          {{ row.displays?.renewDate }}
        </template>
      </el-table-column>
      <el-table-column label="mj模式" prop="mode" width="100">
      </el-table-column>
      <el-table-column label="niji模式" prop="nijiMode" width="100">
      </el-table-column>
      <el-table-column label="禁用原因" width="150" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.properties?.disabledReason }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        :align="`center`"
        fixed="right"
        class-name="small-padding fixed-width"
        width="200"
      >
        <template #default="{ row }">
          <el-tooltip content="新增当前token下所有频道账号池" placement="top">
            <el-button type="primary" link @click="batchAdd(row)">
              批量新增
            </el-button>
          </el-tooltip>
          <el-button type="primary" link @click="tokenLinkData(row)">
            查看所有账号
          </el-button>
          <!-- <el-button type="primary" link @click="channelLLinkData(row)">
            频道关联账号
          </el-button> -->
          <!-- <el-tooltip content="删除" placement="top">
            <el-button link type="danger" icon="Delete" @click="deleteHandler(row)"></el-button>
          </el-tooltip> -->
        </template>
      </el-table-column>
    </el-table>

    <!-- <Pagination
      v-show="total > 0"
      :total="total"
      v-model:page="pagination.current"
      v-model:limit="pagination.size"
      @pagination="getList"
    /> -->
    <el-dialog :title="title" v-model="open" width="1400px" append-to-body>
      <div style="height: 75vh; overflow: hidden">
        <!-- 表格数据 -->
        <el-table height="100%" v-loading="linkLoading" :data="linkData" :row-style="subRowStyle">
          <el-table-column label="授权码" prop="key" width="160">
          </el-table-column>
          <el-table-column label="token" prop="token" width="400">
            <template #default="{ row }">
              <span
                :class="{
                  'on-success': row.online === true,
                  'on-error': row.online === false,
                }"
                >{{ row.token }}</span
              >
            </template>
          </el-table-column>
          <el-table-column label="调用次数" prop="count"> </el-table-column>
          <el-table-column
            label="快速模式使用次数"
            prop="fastUseCount"
            width="160"
          >
          </el-table-column>
          <el-table-column
            label="快速模式总次数"
            prop="fastMaxCount"
            width="160"
          >
          </el-table-column>
          <el-table-column
            label="relax模式使用次数"
            prop="relaxUseCount"
            width="160"
          >
          </el-table-column>
          <el-table-column
            label="relax模式总次数"
            prop="relaxMaxCount"
            width="160"
          >
          </el-table-column>
          <el-table-column label="到期时间" prop="expireTime" width="180">
          </el-table-column>

          <el-table-column label="备注" prop="remark" width="160">
          </el-table-column>
          <el-table-column label="菜单id" prop="guildId" width="180">
          </el-table-column>
          <el-table-column label="频道id" prop="channelId" width="180">
          </el-table-column>
          <el-table-column
            label="操作"
            :align="`center`"
            fixed="right"
            class-name="small-padding fixed-width"
            width="160"
          >
            <template #default="{ row }">
              <el-tooltip v-if="getContent(row)" :content="getContent(row)" placement="top">
                <el-button type="primary" link disabled @click="handleAdd(row)">
                  新增账号池账号
                </el-button>
              </el-tooltip>
              <el-button v-else type="primary" link :disabled="!getStatus(row)" @click="handleAdd(row)">
                新增账号池账号
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
    <!-- 新增账号 -->
    <el-dialog title="新增账号池账号" v-model="addVisible" width="700px" append-to-body>
      <el-form ref="addRef" :inline="false" :model="form" :rules="rules" label-width="140px">

        <el-form-item label="token" prop="token">
          <el-input v-model.trim="form.token" placeholder="请输入token" />
        </el-form-item>

        <el-form-item label="服务器id" prop="guildId">
          <el-input disabled v-model.trim="form.guildId" placeholder="请输入服务器id" />
        </el-form-item>
        <el-form-item label="频道id" prop="channelId">
          <el-input disabled v-model.trim="form.channelId" placeholder="请输入频道id" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input :rows="3" type="textarea" v-model.trim="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" :loading="formLoading">确 定 </el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 批量新增账号 -->
    <el-dialog title="批量新增账号池账号" v-model="batchVisible" width="700px" append-to-body>
      <el-form ref="addRef" :inline="false" :model="batchForm" :rules="rules" label-width="140px">

        <el-form-item label="token" prop="token">
          <el-input v-model.trim="batchForm.token" placeholder="请输入token" />
        </el-form-item>

        <el-form-item label="频道id" prop="channelIds">
          <el-select v-model="batchForm.channelIds" multiple placeholder="请选择频道id" style="width: 100%">
            <el-option
              v-for="item in linkData"
              :key="item.channelId"
              :label="item.channelId"
              :value="item.channelId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input :rows="3" type="textarea" v-model.trim="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitBatch" :loading="formLoading">确 定 </el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 批量新增账号 -->
    <el-dialog title="批量新增账号池账号" v-model="allVisible" width="1400px" height="700px" append-to-body>
      <TableForm
        ref="batchRef"
        height="100%"
        :value="batchData"
        :isSelection="false"
        :columns="columns"
        @input="tableFormInput"
      ></TableForm>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitALL" :disabled="!batchData.length" :loading="formLoading">确 定 </el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { getPoolAccount, getStoreAccount, addStoreAccount, removeStoreAccount } from '@/api/pool.js'
import { listApi } from '@/api/base/index.js'
import { ElMessageBox, ElMessage, dayjs } from 'element-plus'
import TableForm from './TableForm/TableForm.vue'

const poolList = ref([])
// const storeList = ref([])
const loading = ref(false)
const formRef = ref()
const title = ref('')
const open = ref(false)
const addVisible = ref(false)
const batchVisible = ref(false)
const allVisible = ref(false)
const linkLoading = ref(false)
const linkData = ref([])
const addRef = ref()
const batchRef = ref()
const batchForm = ref({
  token: '',
  channelIds: [],
  guildId: []
})

const data = reactive({
  form: {},
  queryParams: {
    channelId: null,
    enable: '',
    mode: null,
    remark: null
  },
  rules: {
    token: [{ required: true, message: "token不能为空", trigger: "blur" }],
    guildId: [{ required: true, message: "服务器id不能为空", trigger: "blur" }],
    channelIds: [{ required: true, message: "服务器id不能为空", trigger: "change" }],
    channelId: [{ required: true, message: "频道id不能为空", trigger: "blur" }],
  },
  formLoading: false,
  batchData: []
})

const { queryParams, form, rules, formLoading, batchData } = toRefs(data)

const columns = [{
  label: 'token',
  prop: 'token',
  required: true,
  uniqueness: true,
  align: 'center'
}, {
  label: '菜单id',
  prop: 'guildId',
  align: 'center',
  required: true,
  uniqueness: true
}, {
  label: '频道id',
  prop: 'channelId',
  align: 'center',
  required: true,
  uniqueness: true
}]

const poolHash = computed(() => {
  return poolList.value.reduce((cache, item) => {
    cache[item.userToken] = item
    return cache
  }, {})
})

getList()

function getList() {
  loading.value = true
  getPoolAccount(
    { 
      ...queryParams.value,
      current: 1,
      pageNumber: 0,
      pageSize: 30000 // 尽量获取所有数据，后续自定义接口通过token去过滤
    },
    {
      'content-type': 'application/json',
      'mj-api-secret': 'dffdf454l45s93ljs22sddsya'
    }
  )
    .then((response) => {
      poolList.value = response.data.content
      loading.value = false
      // getStoreAccount({
      //   ...queryParams.value
      // })
      //   .then((data) => {
      //     storeList.value = data.map(d => {
      //       const pool = poolHash.value[d.token] || {}
      //       return {
      //         ...pool,
      //         ...d
      //       }
      //     })
      //     loading.value = false
      //   })
      //   .catch(() => {
      //     loading.value = false
      //   })
    })
    .catch(() => {
      loading.value = false
    })
}

function getStatus (row) {
  return dayjs().isBefore(dayjs(row.expireTime)) 
}

function getContent(row) {
  const isExpire = !dayjs().isBefore(dayjs(row.expireTime))
  if (isExpire) {
    return '账号已过期'
  }
  if (row.fastMaxCount <= row.fastUseCount) {
    return '快速模式已用完'
  }
  return ''
} 


function resetQuery() {
  if (!formRef.value) return
  formRef.value.resetFields()
}

/** 搜索按钮操作 */
function handleQuery() {
  getList()
}

/** 多选框选中数据 */
// function handleSelectionChange(selection) {}

// 查看token关联账号
function tokenLinkData(row) {
  open.value = true
  title.value = `【${row.userToken}】关联账号列表`
  getLinkData({
    token: row.userToken
  })
}

// function channelLLinkData(row) {
//   open.value = true
//   getLinkData({
//     channelId: row.channelId
//   })
// }

// 获取关联数据
function getLinkData(params) {
  linkLoading.value = true
  listApi({
    ...params,
    pageNo: 1,
    pageSize: 1000
  })
    .then((response) => {
      linkData.value = response.rows
    })
    .finally(() => {
      linkLoading.value = false
    })
}

const minTime = 0.1
// 行样式处理快速模式快使用完提示
function rowStyle({ row }) {
  if (!row.fastTimeRemaining) {
    return {
      color: '#F56C6C'
    }
  }
  const fastTime = row.fastTimeRemaining.split('/')[0]
  if (parseFloat(fastTime) <= minTime) {
    return {
      color: '#E6A23C'
    }
  }
}

// 行样式处理快速模式快使用完提示
function subRowStyle({ row }) {
  const isExpire = !dayjs().isBefore(dayjs(row.expireTime))
  if (isExpire) {
    return {
      color: '#67c23a'
    }
  }
  if (row.fastMaxCount <= row.fastUseCount) {
    return {
      color: '#E6A23C'
    }
  }
}

// 批量新增
function batchAdd (row) {
  listApi({
    token: row.userToken,
    pageNo: 1,
    pageSize: 1000
  })
  .then((response) => {
    title.value = `【${row.userToken}】关联频道-账号池新增`
    linkData.value = response.rows.filter(d => d.channelId)
    batchForm.value = {
      token: '',
      channelIds: linkData.value.map(d => d.channelId),
      guildId: linkData.value.map(d => d.guildId)
    }
    batchVisible.value = true;
  })
}

// 全局批量新增
function batchAddAll () {
  allVisible.value = true
  batchData.value = []
}

const addBatch = async (list, i) => {
  if(i >= list.length) {
    // await addStoreAccount(unref(form.value));
    ElMessage.success("批量新增成功")
    batchVisible.value = false;
    allVisible.value = false;
    getList();
    return
  }
  await addStoreAccount(list[i])
  await addBatch(list, i + 1)
}

// 批量新增
function submitBatch(){
  addRef.value.validate(async (valid) => {
    if (valid) {
      formLoading.value = true;
      try {
        const channelIdHash = linkData.value.reduce((hash, d) => {
          hash[d.channelId] = d.guildId
          return hash
        }, {})
        const data = batchForm.value.channelIds.map(channelId => {
          return {
            token: batchForm.value.token,
            channelId,
            guildId: channelIdHash[channelId],
            remark: batchForm.value.remark
          }
        })
        await addBatch(data, 0)
      } catch (error) {}
      formLoading.value = false;
    }
  });
}

// 新增操作
function handleAdd(row) {
  form.value = {
    channelId: row.channelId,
    guildId: row.guildId
  }
  addVisible.value = true;
}

// 新增账号
function submitForm() {
  addRef.value.validate(async (valid) => {
    if (valid) {
      formLoading.value = true;
      try {
        await addStoreAccount(unref(form.value));
        ElMessage.success("新增成功")
        addVisible.value = false;
        getList();
      } catch (error) {}
      formLoading.value = false;
    }
  });
}
function cancel() {
  batchVisible.value = false
  addVisible.value = false;
  allVisible.value = false
}


// 删除操作
// function deleteHandler (row) {
//   ElMessageBox.confirm("是否确认删除数据项?")
//     .then(function () {
//       return removeStoreAccount(row);
//     })
//     .then(() => {
//       getList();
//       ElMessage.success("删除成功");
//     })
//     .catch(() => {});
// };

// 批量新增
function tableFormInput (value) {
  batchData.value = value
}

function submitALL () {
  batchRef.value.validate(async valid => {
    if (valid) {
      formLoading.value = true;
      try {
        await addBatch(batchData.value, 0)
        getList();
      } catch (error) {}
      formLoading.value = false;
    }
  })
}
</script>

<style></style>
